<?php
if ( class_exists( 'WP_Import' ))
{
    class WilokeImport extends WP_Import
    {
        public $theme_options_name;
        public $default_configs;
        public $aErrors = array();
        public function __construct($default_configs)
        {
            
            parent::__construct();
            $this->default_configs = $default_configs;
        }


        public function set_widgets()
        {
            if(isset($this->default_configs['widgets']) && is_array($this->default_configs['widgets']) && count($this->default_configs['widgets'])>0)
            {
                update_option('sidebars_widgets', '');
                foreach($this->default_configs['widgets'] as $sidebar => $widgets)
                    if(is_array($widgets) && count($widgets)>0)
                        foreach($widgets as $widget => $options)
                            $this->add_widget_sidebar($sidebar,$widget,$options[0],$options[1]);
            }
        }



        public function set_menus()
        {
            //get all registered menu locations
            $locations = get_theme_mod('nav_menu_locations');
            // get all created menu
            $created_menus = wp_get_nav_menus();
            $founded = false;
            if(!empty($created_menus) && is_array($this->default_configs))
            {
                foreach($created_menus as $menu)
                {
                    if(is_object($menu))
                    {
                        if($menu->name == $this->default_configs['menus']['menu_name'])
                        {
                            //if we have found a menu with the correct menu name apply the id to the menu location
                            $locations[$this->default_configs['menus']['menu_id']] = $menu->term_id;
                            echo "<p class=\"success\">Set default menu successfully!</p>";
                            set_theme_mod( 'nav_menu_locations', $locations);
                            $founded = true;
                        }
                    }
                }
            }
            if(!$founded)
                echo "<p class=\"error\">Can not set default menu!</p>";
        }

        public function set_static_page()
        {
            update_option('show_on_front', 'page');
            
            $args = array('post_type'=>'page', 'posts_per_page'=>-1);

            $pages = get_posts($args);

            if ( !empty($pages) && !is_wp_error($pages)  )
            {
                foreach ($pages as $page) : setup_postdata($page);
               
                    if ( get_the_title($page->ID) != 'Home Page' )
                    {
                        continue;
                    }else{
                        update_option('page_on_front', $page->ID);
                    }

                endforeach;
            }

            update_option('posts_per_page', 4);

            if ( function_exists('flush_rewrite_rules') )
            {
                flush_rewrite_rules();
            }
        }

        public function add_widget_sidebar($sidebarSlug, $widgetSlug, $countMod, $widgetSettings = array())
        {
            $sidebarOptions = get_option('sidebars_widgets');
            if(!isset($sidebarOptions[$sidebarSlug])){
                $sidebarOptions[$sidebarSlug] = array('_multiwidget' => 1);
            }
            $newWidget = get_option('widget_'.$widgetSlug);
            if(!is_array($newWidget))$newWidget = array();
            $count = count($newWidget)+1+$countMod;
            $sidebarOptions[$sidebarSlug][] = $widgetSlug.'-'.$count;

            $newWidget[$count] = $widgetSettings;

            update_option('sidebars_widgets', $sidebarOptions);
            update_option('widget_'.$widgetSlug, $newWidget);
        }

        public function remove_all_posts()
        {   
            $posts = get_posts( array("post_type"=>"post", "posts_per_page"=>-1) );

            foreach ( $posts as $post ) : setup_postdata($post);
                wp_delete_post($post->ID);
            endforeach;wp_reset_postdata();

            $pages = get_posts( array("post_type"=>"page", "posts_per_page"=>-1) );

            foreach ( $pages as $page ) : setup_postdata($page);
                wp_delete_post($page->ID);
            endforeach;wp_reset_postdata();
        }

        public function update_theme_options()
        {
            $fileName = isset($this->default_configs['options']['filename']) ? $this->default_configs['options']['filename'] : '';
            $key      = isset($this->default_configs['options']['keyoptions']) ? $this->default_configs['options']['keyoptions'] : '';

            if (empty($fileName) || empty($key))
            {
                $aErrors[]  =  '<p class="error">Empty key or data</div>';    
            }

            if ( empty($aErrors) )
            {
                
                $directFile  = QVA_DEFS . "qva-options.php";

                if ( !file_exists($directFile) )
                {
                    $aErrors[] = "<p class='error'>Files doest not exist!</p>";
                }else{

                    $getContent = file_get_contents($directFile);

                    if ( !empty($getContent) )
                    {
                        $getContent = stripslashes($getContent);
                        $getContent = $this->fix_corrupted_serialized_string($getContent);

                        $content = unserialize($getContent);

                        delete_option($key);
                        
                        update_option($key, $content);
                    }else{
                        $aErrors[] = '<p class="error">Empty the qva-options data</p>';
                    }
                }
            }

            if ( !empty($aErrors) )
            {
                foreach ($aErrors as $error)
                {
                    echo $error . "\n";
                }
            } 
        }


        public  function fix_corrupted_serialized_string($string) 
        {
            $tmp = explode(':"', $string);
            $length = count($tmp);
            for($i = 1; $i < $length; $i++) {    
                list($string) = explode('"', $tmp[$i]);
                $str_length = strlen($string);    
                $tmp2 = explode(':', $tmp[$i-1]);
                $last = count($tmp2) - 1;    
                $tmp2[$last] = $str_length;         
                $tmp[$i-1] = join(':', $tmp2);
            }
            return join(':"', $tmp);
        } 

    }
}